package com.service.core.http;

import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class OptionsRequestHandler {

    /**
     * 预检请求(用于处理跨域访问的复杂请求)
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return boolean
     */
    public static boolean handleOptions(HttpServletRequest request, HttpServletResponse response, String[] allowedOrigins, String allowedMethods) {
        String method = request.getMethod();
        // 如果不是80端口,需要将端口加上,如果是集群,则用Nginx的地址,同理不是80端口要加上端口
        String originHeader = request.getHeader("Origin") != null ? request.getHeader("Origin").replace(" ", "")
                : request.getHeader("Origin");
        // 判断数组中是否包含请求中的origin，如果包含就做跨域设置，否则就是不被允许跨域的地址，不做跨域设置
        if (Arrays.asList(allowedOrigins).contains(originHeader)) {
            response.setHeader("Access-Control-Allow-Origin", originHeader);
            //XFILENAME,XFILECATEGORY,XFILESIZE 苹果safari 跨域兼容
            response.setHeader("Access-Control-Allow-Headers", "api-version, lang, Authorization, Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE");
            response.setHeader("Access-Control-Allow-Methods", allowedMethods);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            if ("OPTIONS".equals(method)) {
                response.setStatus(HttpStatus.OK.value());
                return true;
            } else {
                return false;
            }
        }
        return false;
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,DELETE,PUT,OPTIONS");
//        response.setHeader("Access-Control-Allow-Headers", "api-version, lang, Authorization, Content-Type");
//        if ("OPTIONS".equals(method)) {
//            response.setStatus(HttpStatus.OK.value());
//            return true;
//        } else {
//            return false;
//        }
    }
}